import base64
import io
import json
import time

from PIL import Image
from flask import Flask, request

from dto.ReqLog import ReqLog
from dto.R import R
from util.MilvusUtil import milvusSingle
from util.Queue import data_queue, infoIn

app = Flask(__name__)


@app.route("/milvus/test", methods=['POST'])
def test():
    data = request.get_data()
    try:
        j_data = json.loads(data)
        url = j_data["url"]
    except Exception as err:
        data_queue.put(ReqLog("查询图片", data, {err}.pop().args[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())).to_json())
        return
    resp = [12, 34, 56, 78];
    # 开始运行
    data_queue.put(
        ReqLog("查询图片", data.decode(), resp, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())).to_json())
    return resp;


@app.route("/milvus/query", methods=['POST'])
def query2():
    r = R();
    try:
        t1 = time.time()
        data = request.get_data()
        j_data = json.loads(data)
        byte_data = j_data["byteData"]
        image_bytes = io.BytesIO(base64.decodebytes(byte_data.encode('utf-8')))
        image = Image.open(image_bytes)
        t2 = time.time()
        infoIn("图片转换  " + str(t2 - t1))
        res = milvusSingle.__query__(image)
        t3 = time.time()
        infoIn("查询图片  " + str((t3 - t2)))
        r.__success__(json.dumps(res));
    except Exception as err:
        r.__fail__({err}.pop().args[0])
    resp = json.dumps(r.__dict__)
    #记日志
    data_queue.put(ReqLog("查询图片", simpleReq(j_data), resp, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())).to_json())
    return resp;


@app.route("/milvus/delete", methods=['POST'])
def delete():
    r = R();
    try:
        data = request.get_data()
        ids = json.loads(data)
        res = milvusSingle.__remove__(ids)
        r.success(json.dumps(res.__dict__))
    except Exception as err:
        r.__fail__({err}.pop().args[0])
    #记日志
    resp = json.dumps(r.__dict__);
    data_queue.put(ReqLog("删除图片", ids, resp, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())).to_json())
    return


@app.route("/milvus/insert", methods=['POST'])
def insert():
    r = R();
    try:
        t1 = time.time()
        data = request.get_data()
        j_data = json.loads(data)
        byte_data = j_data["byteData"]
        image_bytes = io.BytesIO(base64.decodebytes(byte_data.encode('utf-8')))
        image = Image.open(image_bytes)
        t2 = time.time()
        infoIn("图片转换  " + str(t2 - t1))
        res = milvusSingle.__insert__(image, j_data["url"], j_data["sku"], j_data["nwSku"]);
        r.__success__(res.primary_keys[0])
    except Exception as err:
        r.__fail__({err}.pop().args[0])
    resp = json.dumps(r.__dict__)
    #记日志
    data_queue.put(ReqLog("保存图片", simpleReq(j_data), resp, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())).to_json())
    return resp;

def simpleReq(j_data):
    j_data["byteData"] = '*'
    return j_data

